Other calculations
The rest of the
calculations on the page follow a similar pattern. For the subtotal, we
can add up our totals for each row as they are calculated, and display
the result using the same currency formatting as before:
$('td.quantity input').change(function() {
var totalQuantity = 0;
var totalCost = 0;
$('#cart tbody tr').each(function() {
var price = parseFloat($('td.price', this).text()
.replace(/^[^\d.*/, ''));
price = isNaN(price) ? 0 : price;
var quantity =
parseInt($('td.quantity input', this).val());
var cost = quantity * price;
$('td.cost', this).text('$' + cost.toFixed(2));
totalQuantity += quantity;
totalCost += cost;
});
$('tr.shipping td.quantity').text(String(totalQuantity));
$('tr.subtotal td.cost').text('$' +
totalCost.toFixed(2));
});
Rounding values
To calculate tax, we need to divide the figure given by 100 and then multiply the taxRate
by the subtotal. As tax is always rounded up, we must ensure that the
correct value is used both for display and for later calculations.
JavaScript's Math.ceil() function can round a number up to the nearest integer, but since we are dealing with dollars and cents we need to be a bit trickier:
var taxRate = parseFloat($('tr.tax td.price').text()) / 100;
var tax = Math.ceil(totalCost * taxRate * 100) / 100;
$('tr.tax td.cost').text('$' + tax.toFixed(2));
totalCost += tax;
The tax is multiplied by 100 first so that it becomes a value in cents, not dollars. This can then be rounded safely by Math.ceil() and then divided by 100 to convert it back into dollars. Finally .toFixed() is called as before to produce the correct result: